package no.ntnu.fp.messages.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.utils.XmlParser;

public class MeetingsForEmployeeMessage implements Message {
	private final Employee employee;
	private final List<Meeting> meetings;
	
	public MeetingsForEmployeeMessage(Employee employee, List<Meeting> meetings) {
		this.employee = employee;
		this.meetings = new ArrayList<Meeting>(meetings);
	}
	
	public MeetingsForEmployeeMessage() {
		this(null, Collections.<Meeting>emptyList());
	}

	public Employee getEmployee() {
		return employee;
	}

	public List<Meeting> getMeetings() {
		return meetings;
	}

	
	@Override
	public MessageCode getMessageCode() {
		return MessageCode.MEETINGS_FOR_EMPLOYEE_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document doc = XmlParser.parseXmlString(xml);
		Employee employee = new Employee((Element)doc.getElementsByTagName("employee").item(0));
		NodeList meetingsNodeList = doc.getElementsByTagName("meeting");
		List<Meeting> meetings = new ArrayList<Meeting>();
		for (int i = 0; i < meetingsNodeList.getLength(); i++) {
			Element appointmentElement = (Element)meetingsNodeList.item(i);
			meetings.add(new Meeting(appointmentElement));
		}
		return new MeetingsForEmployeeMessage(employee, meetings);
	}

	@Override
	public String toString() {
		Document doc = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element messageElement = doc.createElement("message");
		messageElement.appendChild(employee.toXml(doc));
		
		Element meetingsElement = doc.createElement("meetings");
		for (Meeting meeting: meetings) {
			meetingsElement.appendChild(meeting.toXml(doc));
		}
		
		messageElement.appendChild(meetingsElement);
		
		return getMessageCode() + XmlParser.convertXmlToString(messageElement);
	}
}
